//
//  BrowPhotoView.m
//  BuyWhat
//
//  Created by 孟学浩 on 16/12/16.
//  Copyright © 2016年 吕金状. All rights reserved.
//

#import "BrowPhotoView.h"
#import "PhotoCollectionViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "UIView+Toast.h"

@interface BrowPhotoView()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UIButton *saveBtn;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,assign) NSUInteger selectIndex;

@end

@implementation BrowPhotoView

- (instancetype)initWithFrame:(CGRect)frame array:(NSArray *)array selectIndex:(NSUInteger)selectIndex{
    CGRect rect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    if (self = [super initWithFrame:rect]) {
        if (!array || array.count == 0) {
            return self;
        }
        self.alpha = 0;
        self.dataArray = array;
        self.selectIndex = selectIndex;
        self.backgroundColor = [UIColor blackColor];
        [self addSubview:self.collectionView];
        [self addSubview:self.titleLabel];
        [self addSubview:self.saveBtn];
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:selectIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        [self show];
    }
    return self;
}

- (void)show{
    [[[UIApplication sharedApplication].delegate window] addSubview:self];
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 1;
    }];
}

- (void)dismiss{
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)saveEvent{
    PhotoCollectionViewCell *cell = [self.collectionView.visibleCells firstObject];
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:cell.imgUrl]];
    UIImage *img = [UIImage imageWithData:data];
    
    __block ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
    [lib writeImageToSavedPhotosAlbum:img.CGImage metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
        if (error) {
            [self makeToast:@"保存失败" duration:1 position:CSToastPositionCenter];
        }else{
            [self makeToast:@"保存成功" duration:1 position:CSToastPositionCenter];
        }
    }];
}

#pragma mark - UICollectionViewDelegate,UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
 

    PhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([PhotoCollectionViewCell class]) forIndexPath:indexPath];
    NSLog(@"self.dataArray === %@",self.dataArray);
    
    
    cell.imgUrl = self.dataArray[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self dismiss];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
       self.titleLabel.text = [NSString stringWithFormat:@"%d/%ld",(int)(scrollView.contentOffset.x/SCREEN_WIDTH)+1,self.dataArray.count];
}

#pragma mark - set & get

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
        _collectionView.pagingEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.bounces = NO;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([PhotoCollectionViewCell class])];
        _collectionView.backgroundColor = [UIColor blackColor];
    }
    return _collectionView;
}

- (UIButton *)saveBtn{
    if (!_saveBtn) {
        _saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-80, 30, 60, 30)];
        [_saveBtn setTitle:@"保存" forState:UIControlStateNormal];
        _saveBtn.titleLabel.font = DEF_FontSize_15;
        [_saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_saveBtn addTarget:self action:@selector(saveEvent) forControlEvents:UIControlEventTouchUpInside];
        _saveBtn.layer.masksToBounds = YES;
        _saveBtn.layer.cornerRadius = 3;
        _saveBtn.layer.borderColor = [UIColor whiteColor].CGColor;
        _saveBtn.layer.borderWidth = .5;
    }
    return _saveBtn;
}

- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        _titleLabel.center = CGPointMake(SCREEN_WIDTH/2. , self.saveBtn.center.y);
        _titleLabel.text = [NSString stringWithFormat:@"%ld/%ld",self.selectIndex+1,self.dataArray.count];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = DEF_FontSize_15;
    }
    return _titleLabel;
}

@end
